package com.example.demo.interceptors;

import com.example.demo.utils.ApiResponse;
import com.example.demo.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }

        String token = request.getHeader("token");
        if (token != null) {
            try {
                if (JwtUtil.verify(token)) {
                    // 解析用户ID和类型，确保不为空
                    String userId = JwtUtil.getId(token);
                    String userType = JwtUtil.getUserTypeFromToken(token);
                    if (userId == null || userType == null || userId.trim().isEmpty() || userType.trim().isEmpty()) {
                        // 用户ID或类型为空
                        setErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "Token解析错误，缺少必要的用户信息");
                        return false;
                    }

                    if ("user".equals(userType)) {
                        // 用户类型为user，放行
                        return true;
                    } else {
                        // 用户类型不符，响应无权访问
                        setErrorResponse(response, HttpServletResponse.SC_FORBIDDEN, "无权访问");
                        return false;
                    }
                } else {
                    // Token无效
                    setErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "无效的Token");
                    return false;
                }
            } catch (Exception e) {
                // 处理解析Token时的异常
                setErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
                return false;
            }
        } else {
            // 缺少Token
            setErrorResponse(response, HttpServletResponse.SC_BAD_REQUEST, "缺少Token");
            return false;
        }
    }

    private void setErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        response.setContentType("application/json");
        ApiResponse apiResponse = new ApiResponse(status, message, null);
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(apiResponse));
    }
}
